<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\User;
use app\admin\model\MpType;
use app\admin\model\Configuration;
use app\admin\model\OrderLog;
use app\admin\model\UserFraze;
use app\admin\model\ChatMessage;
use app\admin\model\ShopOrder;
use app\admin\model\SearchHistory;
use app\admin\model\Product;
use app\admin\model\ProductWish;
use app\admin\model\ProductMessage;
use app\admin\model\ConfigData;
use app\admin\model\Article;
use app\admin\model\ProductViewLog;
use app\admin\model\UserRoseLog;
use app\admin\model\UserOrder;
use app\admin\model\Slideshow;
use app\admin\model\SArea;
use getui\GeTui;
use function PHPSTORM_META\map;
use think\Db;
use think\Exception;

/**
 * 订单控制器
 */
class Order extends Api
{
	protected $noNeedLogin = ['notifyx','temporary_order_cancel'];

	public function _initialize(){
		$action = request()->action();
	
		if(!in_array($action,$this->noNeedLogin)){
			$ignore = array('host','accept','content-length','content-type');
			$headers = array();
			if($this->request->request('token')){
				$headers['token'] = $this->request->request('token');
			}else{
				foreach($_SERVER as $key=>$value){
					if(substr($key, 0, 5)==='HTTP_'){
						$key = substr($key, 5);
						$key = str_replace('_', ' ', $key);
						$key = str_replace(' ', '-', $key);
						$key = strtolower($key);
						if(!in_array($key, $ignore)){
							$headers[$key] = $value;
						}
					}
				}
			}
			$token=$headers['token'];
			if(strlen($token)!=32){
				$this->error('请登录');
			}
			$this->user=User::where(array('token'=>$token))->find();
			if(!$this->user){
				$this->error('请登录');
			}
			if($this->user['status'] != 1){
                $this->error('账号异常');
            }
			User::where(array('id'=>$this->user['id']))->update(array('active_time'=>time()));
		}
	}

	//获取订单列表
	public function getOrderList(){
		$page=$this->request->request('page',1);
		$pagesize=$this->request->request('pagesize',10);
		$orderList = UserOrder::where(['user_id'=>$this->user['id'],'status'=>2])->limit(($page-1)*$pagesize,$pagesize)->order('add_time desc')->select();
		foreach ($orderList as &$v) {
			$v['paytime'] = date('Y-m-d H:i:s',$v['paytime']);
		}
		$this->success('操作成功',$orderList);
	}


	//获取订单详情
	public function get_order_detail(){
		$product_id = $this->request->request('product_id');
		$order_id = $this->request->request('order_id');

		$order = UserOrder::where(['id'=>$order_id,'user_id'=>$this->user['id'],'status'=>1])->find();
		if(!$order){
			$this->error('订单错误');
		}

		$product_ids = explode(',',$order['product_ids']);
		foreach ($product_ids as &$v) {
			$v = (int)$v;
		}
		$order['product_ids'] = $product_ids;

		$product_list = [];
		foreach ($product_ids as $vs) {
			$product_list[] = Product::where(['id'=>$vs])->find();
		}
		

		$weight = 0;
		$price = 0;
		foreach ($product_list as $vn) {
			if($vn['weight'] == '1kg'){
				$weights = 1;
			}else if($vn['weight'] == '2kg'){
				$weights = 2;
			}else if($vn['weight'] == '3kg'){
				$weights = 3;
			}else if($vn['weight'] == '4kg'){
				$weights = 4;
			}else if($vn['weight'] == '5kg'){
				$weights = 5;
			}
			$weight = bcadd($weight, $weights, 0);
			$price = bcadd($price, $vn['price'], 2);
		}

		
		$order['product_weight'] = $weight;
		$order['product_price'] = $price;

		$order['address'] = $order['address_province'].$order['address_city'].$order['address_district'].$order['address_detail'];
		$order['yunfei'] =  get_delivery_costs($order);   //get_price(['weight'=>$weight.'kg','city'=>$product_list[0]['city']],$order['address_city']);

		if($order['is_shopping'] == 1){  //商城订单
			$order['freight'] = bcadd($price, $order['yunfei'], 2);
		}else{ //闲置订单
			$order['freight'] =$order['yunfei'];
		}
		
		$order['product_info'] = $product_list[0];
		$order['product_info']['user'] = User::where(['id'=>$order['product_info']['user_id']])->find();
		$res = [];
		if(count($product_list) > 1){
			foreach ($product_list as $k=>$vi) {
				if($k > 0){
					$res[] = $vi;
				}
			}
		}
		$order['product_list'] = $res;
		
		
		$this->success('操作成功',$order);
	}



	//下单操作
	public function place_order(){
		$order_id = $this->request->request('order_id','');
		$odd = $this->request->request('odd','');
		$expressage = $this->request->request('expressage','');
		$day = $this->request->request('day','');
		$time = $this->request->request('time','');
		$order=UserOrder::where(array('order_id'=>$order_id,'status'=>2))->find();
		if(!$order){
			$this->error('参数错误');
		}
		$where = ['status'=>6]; //预约快递
		$data = $this->send_expressage($order,$day,$time);
		if($data){
			$where['taskId'] = $data['taskId'];
			$where['orderId'] = $data['orderId'];
			$where['kuaidinum'] = $data['kuaidinum'];	
		}else{
			$this->error('下单失败,请联系管理员');
		}
		/* if($expressage){
			$where['expressage'] = $expressage;
			$where['odd'] = $odd;
			$where['status'] = 3;
			$where['delivery_time'] = time();
		} */
		UserOrder::where(['id'=>$order['id']])->update($where);
		//发短信
		send_mobile('13554694311','SMS_463599452');
		$this->success('下单成功');
	} 
	//发送快递
	public function send_expressage($order = [],$day = '',$time = ''){
		$product = Product::where(['id'=>$order['product_id']])->find();
		//判断物品重量
		$product['weight'] = str_replace('kg', '', $product['weight']);
		if($product['weight'] < 3){
			$kuaidicom = 'jd';
			$expressage = '京东';
			/* $kuaidicom = 'debangkuaidi';
			$expressage = '德邦'; */
			$serviceType = '标准快递';
		}else{
			$kuaidicom = 'debangkuaidi';
			$expressage = '德邦';
			$serviceType = '德邦大件360';
		}
		UserOrder::where(['id'=>$order['id']])->update(['expressage'=>$expressage]);
		
		$param = [
			'kuaidicom' => $kuaidicom,        
			'recManName' => $order['address_username'],              
			'recManMobile' => $order['address_tel'],                        
			'recManPrintAddr' => $order['address_province'].$order['address_city'].$order['address_district'].$order['address_detail'],           
			'sendManName' => $product['name'],              
			'sendManMobile' =>  $product['phone'],               
			'sendManPrintAddr' =>  $product['province'].$product['city'].$product['area'].$product['address'],                
			'callBackUrl' => $this->request->root(true) . '/api/order/notifyx',          
			'cargo'=>'余享商品',
			'weight'=>$product['weight'],
			"payment"=>"",
			"serviceType"=>$serviceType,
			"weight"=>$product['weight'],
			"remark"=>"",
			"salt"=>"",
			"dayType"=>"",
			"pickupStartTime"=>"",
			"pickupEndTime"=>"",
			"valinsPay"=>"",
			"passwordSigning"=>"N",
			"op"=>"0",
			"pollCallBackUrl"=>"",
			"resultv2"=>"0",
			"returnType"=>"0",
			"siid"=>"",
			"tempid"=>"",
			"printCallBackUrl"=>""
		];
		if($day){
			$param['dayType'] = $day;
		}
		if($time){
			$time = explode('-',$time);
			$param['pickupStartTime'] = $time[0];
			$param['pickupEndTime'] = $time[1];
		}
		$param = json_encode($param, JSON_UNESCAPED_UNICODE);
		$t = time() * 1000;
		$post_data = [

			'key'=>'wlSuxIGP3476',
			'sign'=>strtoupper(MD5($param.$t.'wlSuxIGP3476'.'155d139726d040e88207b0cc03481efa')),
			't'=>$t,
			'param'=>$param
		];

		db('log')->insert(['order_id'=>$order['id'],'text'=>$param,'type'=>'发送快递下单参数','add_time'=>date('Y-m-d H:i:s',time())]);
		
		//$url = 'https://api.kuaidi100.com/apiMock/border?method=bOrder';
		$url = 'https://poll.kuaidi100.com/order/borderapi.do?method=bOrder';
		// 发送post请求
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		$result = curl_exec($ch);
		$data = json_decode($result, true);

		OrderLog::insert(['order_id'=>$order['id'],'text'=>'预约快递','user_id'=>$order['user_id'],'add_time'=>date('Y-m-d H:i:s' ,time()) ,'ship_type'=>1,'status'=>2,'json'=>$result]);
		if($data['result'] && $data['returnCode'] == 200){
			return $data['data'];
		}else{
			db('log')->insert(['order_id'=>$order['id'],'text'=>$result,'type'=>'发送快递下单报错','add_time'=>date('Y-m-d H:i:s',time())]);
			return false;
		}
	}


	//查询快递费用接口
	public function delivery_costs(){
		$order_id = $this->request->request('order_id','');
		$address = $this->request->request('address','');
		$city = $this->request->request('city','');
		$weight = $this->request->request('weight','');
		$product_id = $this->request->request('product_id','');
		
		$order = UserOrder::where(['id'=>$order_id])->find();
		if(!$order){
			if(!$address || !$product_id){
				$this->error('参数错误');
			}
			$order = [];
			$order['product_id'] = $product_id;
			$order['address'] = $address;
			$order['address_city'] = $city;
			$order['id'] = -1;
		}else{
			$order['address'] = $order['address_province'].$order['address_city'].$order['address_district'].$order['address_detail'];
		}
		
		$price = get_delivery_costs($order,$weight);
		if(!$price){
			$this->error('快递查询失败,请联系官方人员');
		}
		$product = Product::where(['id'=>$order['product_id']])->find();
		if(!$product || ($product && $product['type_status'] == 1)){
			$this->success('操作成功',$price);
		}else{
			if($product){
				if($product['type_status'] == 2){ //无偿送
					$this->success('操作成功',$price);
				}elseif($product['type_status'] == 3){ //商城买卖
					$this->success('操作成功',[$price,bcadd($price, $product['price'], 2)]);
				}
			}else{
				$this->error('操作错误');
			}
		}
	}
	/**
     * 支付成功回调
     * @return mixed
     */
    public function notifyx()
    {
        $data = $this->request->request('param');
        $data = str_replace('&quot;', '"', $data);
		$inserArr = [
			'text'=>($data),
			'type'=>'成功回调',
			
		];
        $data = json_decode($data,true);
		if($data['status'] == 200 && $data['message'] == '成功'){
			$info = $data['data'];
			$arr = ['wuliu_status'=>$info['status']];
			if($data['kuaidinum']){
				$arr['kuaidinum'] = $data['kuaidinum'];
			}
			$order = UserOrder::where(['orderId'=>$info['orderId']])->find();
			if($order){
				if($order['status']==6 && ($info['status'] == 10 || $info['status'] == 15  || $info['status'] == 13  || $info['status'] == 15  || $info['status'] == 101) ){  //已发货
					$arr['delivery_time'] = time();
					$arr['status'] = 3;
				}
				UserOrder::where(['id'=>$order['id']])->update($arr);
				$inserArr['order_id'] = $order['id'];
			}else{  //赠送物品
				$order = ProductTake::where(['orderId'=>$info['orderId']])->find();
				if($order){
					if($order['status']==6 && ($info['status'] == 10 || $info['status'] == 15  || $info['status'] == 13  || $info['status'] == 15  || $info['status'] == 101) ){  //已发货
						$arr['delivery_time'] = time();
						$arr['status'] = 2;
						//发货了   给积分
						$price = bcadd($order['num'], 20, 0);
						roseandlog($order['user_id'],$price,33,'赠送物品得积分');
					}
					ProductTake::where(['id'=>$order['id']])->update($arr);
					$inserArr['order_id'] = $order['id'];
				}
			}
		}
		$info = db('log')->where($inserArr)->find();
		if(!$info){
			$inserArr['add_time']=date('Y-m-d H:i:s',time());
			db('log')->insert($inserArr);
		}		
		return json(['result'=>true,'returnCode'=>'200','message'=>'成功']);
    }

	//订单详情
	public function user_order_detail(){
		$id=$this->request->require('order_id');
		$order=UserOrder::where(array('id'=>$id))->find();
		if($order['ship_type']==1 && $order['shipping_fee']==1){
		    $order['order_tips']=ConfigData::where(array('name'=>'shop_1_1'))->getField('value');
		}else{
		    $order['order_tips']='';
		}
		$order['add_time']=date("Y-m-d H:i:s",$order['add_time']);
		$order['product']=Product::where(array('id'=>$order['product_id']))->find();	
		$this->success('获取成功',$order);
	}

    //变更订单状态
    public function setOrderStatus(){
        $type=$this->request->request('type',1);  //1 我买的   2我卖的
        $id=$this->request->request('id','');
        $status=$this->request->request('status','');
        $text=$this->request->request('text','');
        $where = [
            'id'=>$id
        ];
        if($type == 1){
            $where['user_id'] = $this->user['id'];
        }else{
            $where['shop_id'] = $this->user['id'];
        }
        $order = UserOrder::where($where)->find();
        if(!$order){
            $this->error('参数错误');
        }
		$update = ['status'=>$status];
		if($status == 5){
			$update['recieve_time'] = time();
		}

		Db::startTrans();
		try {
			if($status == -1 && $this->user['id'] == $order['shop_id']){ //取消订单操作
				$arr = ['user_id'=>$this->user['id'],'order_id'=>$order['id'],'ship_type'=>$order['ship_type'],'status'=>$order['status'],'add_time'=>date('Y-m-d H:i:s',time())];
				//卖家取消
				$arr['type'] =  1;
				$arr['text'] =  $text;
				$arr['status'] =  0;
				OrderLog::insert($arr);
				Db::commit();
				$this->success('卖家取消订单申请');
			}
			$arr = ['user_id'=>$this->user['id'],'order_id'=>$order['id'],'ship_type'=>$order['ship_type'],'status'=>$order['status'],'add_time'=>date('Y-m-d H:i:s',time())];
			if($status == -1 ){ //取消订单操作
				if($order['ship_type'] == 1){
					//如果是买家付邮则需要退运费
					//待支付的不需要退
					if($order['status'] == 2){
						$arr['text'] = '买家付邮退款';
						if($order['pay_type'] == 'dy'){
							$pay = new Pay();
                            $pay->dy_refund($order,$order['pay_fee'],$this->user['nickname'],$arr);
						}else{
							Pay::doOrderRefund($order,$order['pay_fee'],$this->user['nickname'],$arr);
						}
						order_cancel($order);
					}else{
						$arr['text'] = '待支付订单取消';
						UserOrder::where(['id'=>$order['id']])->update($update);
					}
				}else{
					$arr['text'] = '自提取消订单';
					//退回积分
					roseandlog($order['user_id'],$order['total_money'],18,'取消订单，退回');
					$product=Product::where(array('id'=>$order['product_id']))->find();
					ProductMessage::insert(array('product_id'=>$order['product_id'],'title'=>'买家'.$this->user['nickname'].'取消订单，取消发货:【'.$product['title'].'】','user_id'=>$order['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
					Product::where(array('id'=>$order['product_id']))->update(array('is_sale'=>0));
					UserOrder::where(['id'=>$order['id']])->update($update);
				}

				//买家取消给卖家发送消息
				$geTui = new GeTui();
				//添加成功执行推送逻辑
				$cid = User::where(['id'=>['in',$order['shop_id']]])->value('cid');
				if($cid){
					$geTui->pushToSingleByCid($cid,'订单提醒','您的商品已被买家取消','/pages/user/sellOrder');
				}

			}elseif($status == 5 ){  //完成订单
				$arr['text'] = '完成订单';
				$product=Product::where(array('id'=>$order['product_id']))->find();
				if($product){
					//首次订单完成给奖励
					$redis = redis_init();
					$name = 'add_score_25_'.$product['user_id'];
					$info = $redis->get($name);
					if(!$info){
						//未获取过奖励则直接给奖励
						roseandlog($product['user_id'],3,25,'首次订单完成');
						$redis->set($name,time());
					}
					if($order['is_shopping'] == 1){  //商城订单成交
						order_edit_price($product['user_id'],$order['price']);	
					}else{ //积分兑换订单成交
						roseandlog($product['user_id'],$order['total_money'],6,'售出商品获得');
					}
					
					ProductMessage::insert(array('product_id'=>$order['product_id'],'message_id'=>0,'title'=>'自动确认收货，交易商品:【'.$product['title'].'】','user_id'=>$order['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
				}

				UserOrder::where(['id'=>$order['id']])->update($update);
			}elseif($status == 3 ){  //确认发货
				$arr['text'] = '确认发货';
				UserOrder::where(['id'=>$order['id']])->update($update);
			}
			OrderLog::insert($arr);
			Db::commit();
			$this->success('操作成功');
			
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}

    }

	//变更订单状态
	public function setShopOrderStatus(){
        $id=$this->request->request('id','');
        $status=$this->request->request('status','');
        $where = [
            'id'=>$id
        ];
        $where['user_id'] = $this->user['id'];
        $order = ShopOrder::where($where)->find();
        if(!$order){
            $this->error('参数错误');
        }
		$update = ['status'=>$status];
		Db::startTrans();
		try {
			if($status == -1){ //取消订单操作
				ShopOrder::where(['id'=>$order['id']])->update($update);
				Db::commit();
				$this->success('操作成功');
			}
			Db::commit();
			$this->error('操作失败');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
    }

	//更新评价状态
	public function evaluate(){
		$order_id = $this->request->request('order_id');
		$commentId = $this->request->request('commentId');
		$res = UserOrder::where('id',$order_id)->update(['commentId'=>$commentId]);
		if($res){
			$this->success('操作成功');
		}else{
			$this->error('操作失败');
		}
	}

	//催发货
	public function expedite(){
		$id = $this->request->request('id','');
		$order = UserOrder::where(['id'=>$id,'user_id'=>$this->user['id']])->find();
		if(!$order){
			$this->error('参数错误');
		}
		//判断当天是否已经催发货一次  如果已经催过则第二天才能再催
		$redis = redis_init();
		$name = $order['user_id'].$order['id'];
        $info = $redis->get($name);
        if($info){
			//判断时间
			$time1 = date('Y-m-d',$info);
			$time2 = date('Y-m-d',time());
			if($time1 == $time2){
				$this->error('每天只能催发货一次哦');
			}
        }
		$redis->set($name,time());

		//官方客服发送给卖方一条私信
		$arr = [
			'content' => '你有一笔待发货订单，请及时预约快递发货。',
			'user_id' => 439,
			'js_user_id'=> $order['shop_id'],
			'product_id'=>$order['product_id'],
			'add_time'=>time(),
		];
		$arr['sort'] = $arr['js_user_id'].'0'.$order['product_id'].$arr['user_id'];
		ChatMessage::insert($arr);
		$data = [
			"character_string1"=>["value"=>$order['order_id']],
			"thing2"=>[ "value"=> '你有一笔待发货订单，请及时预约快递发货。'], 
			"time4"=>["value"=>date('Y-m-d H:i:s',$order['add_time']) ]
		];
		send_subscription($order['shop_id'],'Ij7RyEc_gcTHbbKkANbp1UZzo2q3q3alO_CPuth2jMc','/pages/user/sellOrder',$data);
		$this->success('操作成功');
	}


	//已发货订单，72小时候自动确认收货
    public function auto_recieve(){
        $time=time()-3600*24*3;
        
        //自提
        $where = ['ship_type'=>2,'status'=>['in','2,3'],'add_time'=>['<',$time]];
        //买家付邮
        $where1 = ['ship_type'=>1,'status'=>3,'delivery_time'=>['<',$time]];

        $orders=UserOrder::where($where)
        ->whereOr(function($query) use ($where1){
            $query->where($where1);
        })->select();
        if($orders){
            foreach($orders as $a=>$b){
                UserOrder::where(array('id'=>$b['id']))->update(array('status'=>5,'recieve_time'=>time()));
                $product=Product::where(array('id'=>$b['product_id']))->find();
                if($product){
                    //首次订单完成给奖励
                    $redis = redis_init();
                    $name = 'add_score_25_'.$product['user_id'];
                    $info = $redis->get($name);
                    if(!$info){
                        //未获取过奖励则直接给奖励
                        roseandlog($product['user_id'],3,25,'首次订单完成');
                        $redis->set($name,time());
                    }

                    roseandlog($product['user_id'],$b['total_money'],6,'售出商品获得');
                    ProductMessage::insert(array('product_id'=>$b['product_id'],'message_id'=>0,'title'=>'自动确认收货，交易商品:【'.$product['title'].'】','user_id'=>$b['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                }
            }
        }

        exit('order to complete over');
    }
    // //已发货订单，72小时候自动确认收货
    // public function auto_recieve(){
    //     $id=$this->request->request('id','');
    //     $order = UserOrder::where(array('status'=>['in','1,2,3'],'id'=>$id,'user_id'=>$this->user['id']))->find();
    //     //redis锁定该订单  避免多次确认收货
    //     $redis = redis_init();
    //     $is_sd = $redis->get($id.'_'.$this->user['id']);
    //     if($order &&  !$is_sd){
    //         UserOrder::where(array('id'=>$order['id']))->update(array('status'=>5,'recieve_time'=>time()));
    //         $product=Product::where(array('id'=>$order['product_id']))->find();
    //         if($product){
    //             roseandlog($product['user_id'],$order['total_money'],6,'售出商品获得');
    //             ProductMessage::insert(array('product_id'=>$order['product_id'],'message_id'=>0,'title'=>'自动确认收货，交易商品:【'.$product['title'].'】','user_id'=>$order['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
    //             $redis->set($id.'_'.$this->user['id'],'');
    //         }
    //     }
    // }

	//未支付订单自动取消
    public function no_payment(){
        $time=time()-900;
        //未支付订单
        $where = ['status'=>1,'add_time'=>['<',$time],'ship_type'=>1];
        $orders=UserOrder::where($where)->select();
 
        if($orders){
            foreach($orders as $a=>$b){
                UserOrder::where(array('id'=>$b['id']))->update(array('status'=>-1,'paidui'=>0,'paidui_content'=>''));
				// 取消订单商品状态更新
                Product::where(['id'=>['in',$b['product_ids']]])->update(array('is_sale'=>0));
            }
        }
        exit('order to complete over');
    }


    //获取我的订单列表
    public function user_order(){
        $list = UserOrder::where(['shop_id'=>0])->select();
        foreach ($list as $v) {
            $user_id=Product::where(array('id'=>$v['product_id']))->value('user_id');
            if($user_id){
                UserOrder::where(['id'=>$v['id']])->update(['shop_id'=>$user_id]);
            }
			
        }
		$where=array();
		$type=$this->request->request('type',1);  //1 我买的   2我卖的
		$page=$this->request->request('page',1);
		$type_status=$this->request->request('type_status',1);
		$pagesize=$this->request->request('pagesize',10);
		if($type == 1){
            $where['user_id'] = $this->user['id'];
        }else{
            $where['shop_id'] = $this->user['id'];
			$where['status'] = ['neq',1];
			$where['paidui'] = 0;
        }
		if($type_status == 1){
			$where['is_shopping'] = 0;
		}elseif($type_status == 3){
			$where['is_shopping'] = 1;
		}elseif($type_status == 4){
			$where['is_shopping'] = 0;
			$where['status'] = 2;
			$where['paidui'] = 1;
			$product_ids=UserOrder::where($where)
				->group('product_id')
				->column('product_id');
			$list = Product::where(['id'=>['in',$product_ids]])->select();
			foreach ($list as $k=>&$v) {
				$orders = 	UserOrder::where(['product_id'=>$v['id'],'status'=>2,'paidui'=>1])->select();
				if(!$orders){
					unset($list[$k]);
					continue;
				}
				foreach ($orders as &$vo) {
					$vo['nickname'] = User::where(['id'=>$vo['user_id']])->value('nickname');
					$vo['avatar'] = User::where(['id'=>$vo['user_id']])->value('avatar');
					$vo['add_time'] = timeago($vo['add_time']);
				}
				$v['orders'] = $orders;
			}
			$list = array_values($list);

			$this->success('获取成功',$list);
		}
		

		$subQuery = UserOrder::where($where)->field('max(add_time) as add_time')->group('product_id')->buildSql();

		$list=UserOrder::alias('a')->group("product_id")
			->order("add_time desc")
			->field("a.*")
			->where($where)
			->join("$subQuery b","b.add_time = a.add_time") // 关键点
			->limit(($page-1)*$pagesize,$pagesize)
			->select();
		foreach($list as $a=>&$b){
			if($b['paidui'] == 1 && $b['status'] == 1){
				//未支付排队的订单不显示
				unset($list[$a]);
				continue;
			}

			if($b['is_read'] == 0){
				UserOrder::where(['id'=>$b['id']])->update(['is_read'=>1]);
			}
			$b['residue_time'] = 0;
			//判断订单状态
			if($b['is_shopping'] == 0){
				$shijian = 259200;
			}else{
				$shijian = 864000;
			}
			
			if($b['ship_type'] == 1){ //买家付邮
				if($b['status'] == 3){
					//查看剩余时间
					$b['residue_time'] = ($b['delivery_time']+$shijian)- time();
				}elseif($b['status'] == 1){
					$b['residue_time'] = ($b['add_time']+900)- time();
				}elseif($b['status'] == 2){
					$OrderLog = OrderLog::where(['order_id'=>$b['id'],'user_id'=>$b['shop_id'],'type'=>1,'status'=>0])->find();
					if($OrderLog){
						$b['status'] = 9;
					}else{
						$b['residue_time'] = ($b['add_time']+$shijian)- time();
					}
				}
			}else{
				if($b['status'] == 2 || $b['status'] == 3){
					//查看剩余时间
					$b['residue_time'] = ($b['add_time']+$shijian)- time();
				}
				
			}
            $b['left_time'] = '00：00：00';
			

			$product=Product::where(array('id'=>$b['product_id']))->find();
			if(!$product){
				unset($list[$a]);
				continue;
			}
			$product['imgsa']=explode(',',$product['imgs']);
			if(empty($product['video_img'])){
				$product['video_img']=$product['imgsa'][0];
			}
			if(strstr($product['video_img'], 'mp4')){
				$product['video_img'] = $product['video_img'].'?x-oss-process=video/snapshot,t_1000,m_fast,ar_auto';
			}
			if($type == 1){
				$where = ['id'=>$product['user_id']];

				$b['is_fh'] = true;
				$redis = redis_init();
				$name = $b['user_id'].$b['id'];
				$info = $redis->get($name);
				if($info){
					//判断时间
					$time1 = date('Y-m-d',$info);
					$time2 = date('Y-m-d',time());
					if($time1 == $time2){
						$b['is_fh'] = false;
					}
				}
			}else{
				$where = ['id'=>$b['user_id']];
			}
		
			$b['product'] = $product;

			if(!$b['product_ids']){
				$b['product_ids'] = $b['product_id'];
			}
			$products=Product::where(array('id'=>['in',$b['product_ids']]))->select();
			if(!$products){
				unset($list[$a]);
				continue;
			}
			foreach ($products as $product) {
				$product['imgsa']=explode(',',$product['imgs']);
				if(empty($product['video_img'])){
					$product['video_img']=$product['imgsa'][0];
				}
				if(strstr($product['video_img'], 'mp4')){
					$product['video_img'] = $product['video_img'].'?x-oss-process=video/snapshot,t_1000,m_fast,ar_auto';
				}
				if($type == 1){
					$where = ['id'=>$product['user_id']];
	
					$b['is_fh'] = true;
					$redis = redis_init();
					$name = $b['user_id'].$b['id'];
					$info = $redis->get($name);
					if($info){
						//判断时间
						$time1 = date('Y-m-d',$info);
						$time2 = date('Y-m-d',time());
						if($time1 == $time2){
							$b['is_fh'] = false;
						}
					}
				}else{
					$where = ['id'=>$b['user_id']];
				}
			}
			$b['products'] = $products;
			
			$b['publisher']=User::field('id,avatar,nickname,token,mobile')->where($where)->find();
			if(!$b['publisher']){
				unset($list[$a]);
				continue;
			}
			if($b['ship_type']==1 && $b['shipping_fee']==1){
			    $b['order_tips']=ConfigData::where(array('name'=>'shop_1_1'))->value('value');
			}else{
			    $b['order_tips']='';
			}
            $b['add_time'] = date('Y-m-d H:i:s',$b['add_time']);

			if(!$b['address_username']){
				if($type == 1){
					$where['user_id'] = $this->user['id'];
					$b['address_username'] = User::where(['id'=>$b['shop_id']])->value('nickname');
				}else{
					$b['address_username'] = User::where(['id'=>$b['user_id']])->value('nickname');
				}
				
			}
		}
		$list = array_values($list);
        //rsort($list);
        $this->success('获取成功',$list);
	}

	//排队卖家选中买家操作
	public function order_opt_for(){
		$order_id=$this->request->request('order_id',''); 

		$order = UserOrder::where(['id'=>$order_id,'status'=>2,'paidui'=>1])->find();
		if(!$order){
			$this->error('操作失败');
		}
		//存在则操作
		Db::startTrans();
		try {
			$list = UserOrder::where(['id'=>['neq',$order['id']],'paidui'=>1,'status'=>2,'product_id'=>$order['product_id']])->select();
			if($list){
				//存在则退款
				foreach ($list as $v) {
					$arr = ['user_id'=>$v['id'],'order_id'=>$v['id'],'ship_type'=>$v['ship_type'],'status'=>$v['status'],'add_time'=>date('Y-m-d H:i:s',time())];
					if($v['ship_type'] == 1){
						//如果是买家付邮则需要退运费
						$arr['text'] = '买家付邮退款';
						if($v['pay_type'] == 'dy'){
							$pay = new Pay();
                            $pay->dy_refund($v,$v['pay_fee'],User::where(['id'=>$v['user_id']])->value('nickname'),$arr);
						}else{
							Pay::doOrderRefund($v,$v['pay_fee'],User::where(['id'=>$v['user_id']])->value('nickname'),$arr);
						}
					}
					//买家取消给卖家发送消息
					$geTui = new GeTui();
					//添加成功执行推送逻辑
					$cid = User::where(['id'=>['in',$v['user_id']]])->value('cid');
					if($cid){
						$geTui->pushToSingleByCid($cid,'订单提醒','您的余享排队未被卖家选中,订单已取消','/pages/user/myOrder');
					}
					OrderLog::insert($arr);
				}
			}
			UserOrder::where(['id'=>$order_id])->update(['paidui'=>0]);
			Product::where(['id'=>$order['product_id']])->update(['is_sale'=>1]);
			Db::commit();
			$this->success('操作成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
	}


	public function get_read(){
		$type=$this->request->request('type',1);  //1 我买的   2我卖的
		$where = ['is_shopping'=>1,'is_read'=>0];
		if($type == 1){
            $where['user_id'] = $this->user['id'];
        }else{
            $where['shop_id'] = $this->user['id'];
        }
		$num = UserOrder::where($where)->count();

		$where = [
			'shop_id'=>$this->user['id'],
			'paidui'=>1,
			'status'=>2
		];
		$num_paidui=UserOrder::where($where)
			->group('product_id')
			->count();

		$this->success('获取成功',['num'=>$num,'num_paidui'=>$num_paidui]);

	}

	//更新商品地址
	public function updateAddress(){
		$data = [];
		$data['address']		= $this->request->request('address','');
		$data['province']		= $this->request->request('province','');
		$data['city']			= $this->request->request('city','');
		$data['area']			= $this->request->request('area','');
		$data['name']           = $this->request->request('name');
		$data['phone']          = $this->request->request('phone');
		$id = $this->request->request('id');
		$res = Product::where('id',$id)->update($data);
		if($res){
			$this->success('操作成功');
		}else{
			$this->error('更新寄件地址失败');
		}

	}

	//计算运费
	public function get_freight(){
		$address = $this->request->request('address','');
		$address_tow = $this->request->request('address_tow','');
		$weight = $this->request->request('weight','');
		$product_id = $this->request->request('product_id','');
		$arr = [
			[
				'address'=>10,
				'address_tow'=>12,
			],
			[
				'address'=>11,
				'address_tow'=>15,
			],
			[
				'address'=>13,
				'address_tow'=>16,
			],
			[
				'address'=>14,
				'address_tow'=>20,
			],
			[
				'address'=>15,
				'address_tow'=>25,
			],
		];
		if($weight == '1kg'){
			$i = 0;
		}elseif($weight == '2kg'){
			$i = 1;
		}elseif($weight == '3kg'){
			$i = 2;
		}elseif($weight == '4kg'){
			$i = 3;
		}elseif($weight == '5kg'){
			$i = 4;
		}
		//同城
		if($address == $address_tow){
			$m = 'address';
		}else{
			$m = 'address_tow';
		}
		$product = Product::where(['id'=>$product_id])->find();

		if(!$product || ($product && $product['type_status'] == 1)){
			$this->success('操作成功',$arr[$i][$m]);
		}else{
			if($product){
				if($product['type_status'] == 2){ //无偿送
					$this->success('操作成功',$arr[$i][$m]);
				}elseif($product['type_status'] == 3){ //商城买卖
					$this->success('操作成功',[$arr[$i][$m],bcadd($arr[$i][$m], $product['price'], 2)]);
				}
			}else{
				$this->error('操作错误');
			}
		}

	}

    //生成订单
	public function order_submit(){
	    $order_id=date("YmdHis").rand(1000,9999);
		$data['order_id']=$order_id;
		$data['product_id']=$this->request->request('product_id');
		
		$fraze=UserFraze::where(array('user_id'=>$this->user['id'],'module_id'=>3))->find();
		if($fraze){
            $this->error('您的账号已被限制【兑换宝贝功能】了,解封请联系在线客服');
		}
		if(empty($data['product_id'])){
            $this->error('商品id丢失');
		}
		$product=Product::where(array('id'=>$data['product_id']))->find();
		if($product['is_sale']==1){
            $this->error('此商品已经售出了');
		}
		if($product['user_id']==$this->user['id']){
            $this->error('无法兑换自己的物品!');
		}
        if($product['peisong']=='1,0'){//自提
    		$data['ship_type']=2;
        }else{
    		$data['ship_type']=1;
			//买家付邮提示用户前往小程序进行付款
			//$this->error('请去余享小程序完成下单!');
        }
        $data['shipping_fee']=$product['shipping_fee'];
		$data['user_id']=$this->user['id'];
		$data['status']	=0;
		if($product['price']>$this->user['rose_money']){
            $this->error('余额不足，兑换失败');
		}
		$data['price']=$product['price'];
		$data['quantity']=1;
		$data['total_money']=$product['price'];
		
		$address_id=$this->request->request('address_id');
		$address_id=str_replace('undefined','',$address_id);

		$data['mark']=$this->request->request('mark');
        $data['status']=2;
		$data['add_time']=time();
		
		$repeat=UserOrder::where(array('product_id'=>$data['product_id'],'user_id'=>$data['user_id'],'status'=>1))->find();
		if($repeat){
            $this->error('您已经提交过订单了');
		}
		$oid	=	UserOrder::insert($data);
		if($oid){
			$this->sendOrderSuccess($data,$product);
            $this->success('订单生成成功',$order_id);
		}else{
            $this->error('订单创建失败');
		}
	}


	//下单成功后操作
	public function sendOrderSuccess($data,$product){
		//  下单后标为售出
		Product::where(array('id'=>$data['product_id']))->update(array('is_sale'=>1));
		roseandlog($this->user['id'],0-$data['total_money'],5,'兑换商品扣除');
		ProductMessage::insert(array('product_id'=>$data['product_id'],'message_id'=>0,'title'=>'买家'.$this->user['nickname'].'下单了，请尽快发货:【'.$product['title'].'】','user_id'=>$data['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));

		


		$configuration=Configuration::where(array('id'=>1))->find();
		// 注意使用GMT时间  
		date_default_timezone_set("GMT");  
		$target = "https://dysmsapi.aliyuncs.com/?";  
		$dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601规范  
		$accessKeyId = $configuration['access_key'];      // 这里填写您的Access Key ID  
		$accessKeySecret = $configuration['access_secret'];  // 这里填写您的Access Key Secret  
		$ParamString="{}";
		$mobile=$product['phone'];
		if($product['type_status'] < 3){
            $TemplateCode = 'SMS_274540075';
        }else{
            $TemplateCode = 'SMS_469060207';
        }

		$data = array(  
			'AccessKeyId' => $accessKeyId,
			'Action' => 'SendSms',
			'Format' => 'XML', 
			'OutId' => '123',
			'PhoneNumbers' => $mobile,
			'RegionId' => 'cn-hangzhou',
			'SignName'=>$configuration['sign_name'],
			'SignatureMethod' => 'HMAC-SHA1',
			'SignatureNonce'=> '45e25e9b-0a6f-4070-8c85-'.uniqid(),
			'SignatureVersion' => '1.0',
			'TemplateCode' => $TemplateCode, 
			'TemplateParam' => $ParamString,
			'Timestamp' => date("Y-m-d H:i:s"), 
			'Version' => '2017-05-25'
		);  
		$data['Signature'] = computeSignature($data, $accessKeySecret);  
		// 发送请求  
		$result = xml_to_array(https_request($target.http_build_query($data)));
		//print_r($result);
		if(!empty($result['Error']['Message'])){
			$this->error($result['Error']['Message']);
		}
		if($product['notice'] == 0){
			return true;
		}
		//发送订阅消息
		$data = [
			"thing8"=>["value"=>$product['title']],
			"thing3"=>[ "value"=> '待发货'], 
			"thing4"=>["value"=>'你的闲置已赠出，请去订单页联系买家自提！' ]
		];
		send_subscription($product['user_id'],'UJnRdmFH3FHRqisFtbKCuYJRxHEK1J8sJydn0DToLFg','/pages/user/sellOrder',$data);
	}
	//订单发货订阅
	public function order_notice(){
		$order_id= $this->request->request('order_id',0);
		$notice= $this->request->request('notice',0);
		if($order_id && $notice==1){
			UserOrder::where(array('order_id'=>$order_id))->update(array('notice'=>1));
		}elseif($order_id && $notice==0){
			UserOrder::where(array('order_id'=>$order_id))->update(array('notice'=>0));
		}
		$this->success('操作成功');
	} 

	//下单订阅
	public function product_notice(){
		$product_id= $this->request->request('product_id',0);
		$notice= $this->request->request('notice',0);
		if($product_id && $notice==1){
			Product::where(array('id'=>$product_id))->update(array('notice'=>1));
		}elseif($product_id && $notice==0){
			Product::where(array('id'=>$product_id))->update(array('notice'=>0));
		}
		$this->success('操作成功');
	}



	//临时取消快递接口
	public function temporary_order_cancel(){
		$order_id = $this->request->request('order_id');
		$order = UserOrder::where(['id'=>$order_id])->find();
		$res = order_cancel($order);
		dd($res);

	}



}